# Copyright (c) 2025, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from srm.srm.doctype.srm_server_config.srm_server_config import login_k3cloud
import requests
import json


class HSFReleaseTask(Document):
	
	# 从货源清单关联出供应商
	@frappe.whitelist()
	def get_supplier(self):
		if self.docstatus == 0:
			num = 0
			for row in self.items:
				if not row.supplier:
					sql = f""" SELECT supplier FROM `tabSRM Source Bill Sub` WHERE material_number = '{row.item_code}' """
					res = frappe.db.sql(sql, as_dict=True)
					if len(res) > 0:
						row.supplier = res[0].supplier
						num += 1
			self.save()
			self.reload()
			return num

		else:frappe.throw("已提交不允许执行此操作!")

	# 自动查找此物料号和此供应商是否已发布"环保任务认证",如果有自动更新"发布状态"为"已发布"或"已完成"
	@frappe.whitelist()
	def validate_release_status(self):
		if self.docstatus == 0:
			num = 0
			for row in self.items:
				sql = f""" SELECT release_status FROM `tabHSF Certification Task` WHERE material_number = '{row.item_code}' AND supplier = '{row.supplier}' """
				res = frappe.db.sql(sql, as_dict=True)
				if len(res) > 0:
					if res[0].release_status == 'No':
						# "已发布"
						row.release_status = 'Releasing'
						num += 1
					if res[0].release_status == 'Yes':
						# "已完成"
						row.release_status = 'Finished'
						num += 1
			self.save()
			self.reload()
			return num
		else:frappe.throw("已提交不允许执行此操作!")

	def before_submit(self):
		self.validate_supplier()

	# 取消供应商必填,在提交前强校验
	def validate_supplier(self):
		row_index = []
		for row in self.items:
			if not row.supplier:
				row_index.append(row.idx)
		if len(row_index) > 0:
			rows = '/'.join([str(i) for i in row_index])
			frappe.throw(f"这些行号{rows}供应商为空, 不允许提交!")

	# 生成环保认证任务
	def on_submit(self):
		for item in self.items:
			if item.release_status == "Pending":
				env_task = frappe.new_doc("HSF Certification Task")
				env_task.update({
					# 物料基本信息
					"material_number": item.item_code,
					# 供应商信息
					"supplier": item.supplier,
					"is_notified":'No',
					"applying_for": self.project,
					"environmental_attributes": self.environmental_attributes,
					# 携带行ID
					"release_task_row": item.name
				})
				# 保存文档（忽略权限检查，确保系统用户可以执行）
				env_task.insert(ignore_permissions=True)
				# 修改当前行release_status
				item.release_status = 'Releasing'
		self.save(ignore_permissions=True)

# 递归找出外购子物料
def find_wg_materials(data):
    result = []
    if data.get("Lev", 0) > 0 and data.get("FErpClsID") == "1":
        result.append(data)
    children = data.get("children", [])
    if children:
        for item in children:
            result.extend(find_wg_materials(item))
    return result

# 同步云星空BOM正查结果并写入
@frappe.whitelist()
def sync_bom(docname, org, material_number, bomverson, maxlev=30, qty=1):
	server_config = frappe.db.get_all('SRM Server Config', filters = {'disable': 0}, fields = ['server_url', 'user_name', 'acctid', 'user_password'])
	if len(server_config)>0:
		login_response = login_k3cloud(server_config[0].server_url, server_config[0].acctid, server_config[0].user_name, server_config[0].user_password)
		if login_response:
			view_url = server_config[0].server_url + "JB.LZX.API.Plugin.BOMWebApi.BOM,JB.LZX.API.Plugin.common.kdsvc"
			view_options = {"Org": org, "Material": material_number, "BomVerson": bomverson, "MaxLev": maxlev, "Qty": qty}
			view_response = requests.post(url=view_url, data=view_options, cookies=login_response)
			bom_res = json.loads(view_response.text)
			if bom_res and bom_res["IsSuccess"] == True:
				return find_wg_materials(bom_res["Data"])
				# return bom_res["Data"]
			else:
				frappe.throw(f"BOM清单无法同步!请确认使用组织:{org},成品编码:{material_number},BOM版本号:{bomverson}在云星空物料清单正查有效!")
	else:
		frappe.throw("请检查API配置是否正确!server_config can not get_all!")

